package hashmap

import "fmt"

/* 键值对 */
type Pair struct {
	key int
	val string
}

/* 基于数组实现的哈希表 */
type ArrayHashMap struct {
	buckets  []*Pair
	capacity int
}

func NewArrayHashMap(bucketSize int) *ArrayHashMap {
	return &ArrayHashMap{
		buckets:  make([]*Pair, bucketSize),
		capacity: bucketSize,
	}
}

func (a *ArrayHashMap) hash(k int) int {
	return (k % a.capacity)
}

func (a *ArrayHashMap) Set(k int, v string) {
	a.buckets[a.hash(k)] = &Pair{
		key: k,
		val: v,
	}
}

func (a *ArrayHashMap) Get(k int) string {
	p := a.buckets[a.hash(k)]
	if p != nil {
		return p.val
	}
	return ""
}

func (a *ArrayHashMap) Exist(k int) bool {
	return a.buckets[a.hash(k)] != nil
}

func (a *ArrayHashMap) Delete(k int) {
	if a.Exist(k) {
		a.buckets[a.hash(k)] = nil
		a.capacity--
	}

}

func (a *ArrayHashMap) Keys() []int {
	var res []int
	for _, v := range a.buckets {
		if v == nil {
			continue
		}
		res = append(res, v.key)
	}
	return res
}

func (a *ArrayHashMap) Print() {
	for _, v := range a.buckets {
		if v == nil {
			continue
		}
		fmt.Printf("%d => %v \n", v.key, v.val)
	}
}
